import fs from 'fs'
import path from 'path'
import type { Compiler } from 'webpack';
export interface EnvJsonOption {
    rootPath?: string,
    fileList?: string[],
    all?: boolean
}
class EnvJson {
    #rootPath = "./src"
    #all = true
    constructor(option: EnvJsonOption = { all: true }) {
        this.#rootPath = option.rootPath || this.#rootPath
        this.#all = option.all || this.#all
        this.#jsonFiles = option.fileList || []
    }
    #jsonFiles: string[] = []
    getJsonFiles(dir: string) {
        const files = fs.readdirSync(dir);
        files.forEach(file => {
            const filePath = path.join(dir, file);
            const stat = fs.statSync(filePath);
            if (stat.isDirectory()) {
                this.getJsonFiles(filePath); // 递归处理子文件夹
            } else if (path.extname(filePath) === '.json') {
                this.#jsonFiles.push(filePath); // 将 JSON 文件路径添加到数组中
            }
        });
    }
    apply(compiler: Compiler): any {
        compiler.hooks.afterEmit.tap('AfterEmitPlugin', compilation => {
            if (this.#all) {
                this.getJsonFiles(compiler.options.output.path || this.#rootPath)
            }
            this.#jsonFiles.forEach((p) => {
                let jsonData = fs.readFileSync(p, 'utf-8') || ''
                let match = jsonData.match(/\$\{\s*\w*\s*\}/ig) || []
                match.forEach((data) => {
                    let test = data.replace(/\$\{\s*/, "").replace(/\}\s*/, "").replace(' ', "")
                    jsonData = jsonData.replace(data, process.env[test] || "")
                })
                fs.writeFileSync(p, jsonData, { flag: 'w' });
            })
        });
    }
}
export { EnvJson };